package com.jiyinit.web.core.activiti.service;

import com.jiyinit.core.framework.base.paging.PagingResult;
import com.jiyinit.web.core.activiti.dao.TabLeaveBillInfoDao;
import com.jiyinit.web.core.activiti.dto.LeaveBillRequset;
import com.jiyinit.web.core.activiti.entity.TabLeaveBillInfoEntity;
import com.jiyinit.web.core.activiti.enums.LeaveGateWayEnum;
import com.jiyinit.web.core.activiti.enums.ProcessFlowEnum;
import com.jiyinit.web.core.activiti.vo.TabLeaveBillinfoVo;

import com.jiyinit.web.core.common.config.PropertyPlaceholderConfigurer;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p></p>
 * <p>
 * <PRE>
 * <BR>	修改记录
 * <BR>-----------------------------------------------
 * <BR>	修改日期			修改人			修改内容
 * </PRE>
 *
 * @author jack zh
 * @version 1.0
 * @date 2018/7/17
 * @since 1.0
 */

@Service("leaveBillInfoServiceImpl")
public class LeaveBillInfoServiceImpl {


    private static String LEAVE_DAYS= (String) PropertyPlaceholderConfigurer.getContextProperty("LEAVE_DAYS");
    private static String LEAVE_SPECIAL_ORG= (String) PropertyPlaceholderConfigurer.getContextProperty("LEAVE_SPECIAL_ORG");
    private static String SPECIAL_USER_ID= (String) PropertyPlaceholderConfigurer.getContextProperty("SPECIAL_USER_ID");


    /**
     * 日志对象
     */
    private static Logger logger = LoggerFactory.getLogger(LeaveBillInfoServiceImpl.class);

    @Resource(name = "core.tabLeaveBillInfoDao")
    private TabLeaveBillInfoDao tabLeaveBillInfoDao;

    //工作流相关
    @Resource(name = "runtimeService")
    RuntimeService runtimeservice;
    @Resource(name = "identityService")
    IdentityService identityservice;
    @Resource(name = "taskService")
    TaskService taskservice;


    public int deleteByPrimaryKey(Integer id)
    {
       return tabLeaveBillInfoDao.deleteByPrimaryKey(id);
    }


    public int insert(TabLeaveBillInfoEntity record)
    {
        return tabLeaveBillInfoDao.insert(record);
    }


    public int insertSelective(TabLeaveBillInfoEntity record)
    {
        return tabLeaveBillInfoDao.insertSelective(record);
    }

    public TabLeaveBillInfoEntity selectByPrimaryKey(Integer id)
    {
        return tabLeaveBillInfoDao.selectByPrimaryKey(id);
    }

    public List<TabLeaveBillInfoEntity> findBySelective(TabLeaveBillInfoEntity record)
    {
        return tabLeaveBillInfoDao.findBySelective(record);
    }

    public PagingResult<TabLeaveBillInfoEntity> getUserInfoListByCondiction(LeaveBillRequset record){
        return tabLeaveBillInfoDao.getUserInfoListByCondiction(record);
    }

    public int updateByPrimaryKeySelective(TabLeaveBillInfoEntity record)
    {
        return tabLeaveBillInfoDao.updateByPrimaryKeySelective(record);
    }

    public int updateByPrimaryKey(TabLeaveBillInfoEntity record)
    {
        return tabLeaveBillInfoDao.updateByPrimaryKey(record);
    }


    public ProcessInstance startWorkflow(TabLeaveBillInfoEntity billInfoEntity, String userid) {
        String businesskey=String.valueOf(billInfoEntity.getId());//使用leaveapply表的主键作为businesskey,连接业务数据和流程数据
        Map<String,Object> variables=new HashMap<String, Object>();
        this.setProcessVariables(variables,billInfoEntity);
        identityservice.setAuthenticatedUserId(userid);  //设置用户id
        ProcessInstance instance=runtimeservice.startProcessInstanceByKey(ProcessFlowEnum.Leave.getCode(),businesskey,variables);
        String instanceid=instance.getId();
        billInfoEntity.setExecutionId(instanceid);
        billInfoEntity.setModDate(new Date());
        this.updateByPrimaryKeySelective(billInfoEntity);
        return instance;
    }


    /* txd 添加start*/
    /**
     * 请假信息统计(导出)
     * @param requset
     * @return
     */
    public List<TabLeaveBillinfoVo> findLeaveInfoListForExport(LeaveBillRequset requset){
        return tabLeaveBillInfoDao.findLeaveInfoListForExport(requset);
    }

    /**
     * 请假信息统计(分页, 导出)
     * @param requset
     * @return
     */
    public PagingResult<TabLeaveBillinfoVo> findLeaveInfoListForExportByPage(LeaveBillRequset requset){
        return tabLeaveBillInfoDao.findLeaveInfoListForExportByPage(requset);
    }
    /* txd 添加end*/

    //设置全局变量
    private void setProcessVariables( Map<String,Object> variables,TabLeaveBillInfoEntity billInfoEntity)
    {
        TabLeaveBillInfoEntity record=billInfoEntity;
        // 设置节点拾取人
        variables.put("leaveUserId",record.getUserId()+"");   //设置全局变量方便后面节点调用
        String[] suserIds = SPECIAL_USER_ID.split(",");//特殊申请人数组
        for(String userId : suserIds){
            if(userId.equals(record.getUserId()+"")){//判断是特殊申请人
                //设置后续节点参数
                variables.put(LeaveGateWayEnum.gateway_4.getCode(), "1");  //设置身份
                variables.put(LeaveGateWayEnum.gateway_9.getCode(), "2");  //设置部门
                variables.put(LeaveGateWayEnum.gateway_11.getCode(), "false");  //设置身天数
                return;
            }
        }

        //设置后续节点参数
        variables.put(LeaveGateWayEnum.gateway_4.getCode(), record.getUserLevel());  //设置身份
        //天数判定
        String gateway11res="false";

        if (record.getLvDay() > Integer.parseInt(LEAVE_DAYS)){
            gateway11res="false";
        }else if(record.getLvDay() == Integer.parseInt(LEAVE_DAYS)){
            if(record.getLvHours() > 0){
                gateway11res="false";
            }else{
                gateway11res="true";
            }
        }else{
            gateway11res="true";
        }  //大于指定天数走总经理审批
        variables.put(LeaveGateWayEnum.gateway_11.getCode(), gateway11res);  //设置身天数

        //设置部门
        String orgsFlag="1";
        String[] orgs=LEAVE_SPECIAL_ORG.split(",");
        for (String org:orgs) {
            if(org.equals(record.getOrgId()+""))
            {
                orgsFlag="2";
                break;
            }
        }
        variables.put(LeaveGateWayEnum.gateway_9.getCode(), orgsFlag);  //设置部门

        if("2".equals(record.getUserLevel())){
            variables.put(LeaveGateWayEnum.gateway_9.getCode(), "2");  //设置部门
        }
    }

    /*txd 添加*/
    /**
     * 获取当前用户的待提交的最大id,即为最新id
     * @param userId
     * @return
     */
    public int getMaxIdByUserId(Integer userId){
        return tabLeaveBillInfoDao.getMaxIdByUserId(userId);
    }

    public PagingResult<TabLeaveBillinfoVo> find(LeaveBillRequset request) {
        return tabLeaveBillInfoDao.find(request);
    }

}
